package ca.etsmtl.gti785.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * This class keeps a socket opened for the file transfer. The port of the socket can be set in the config files.
 * @see Constants
 * @author Étienne Faucher
 */
public class SocketListener 
{
	private Thread _runningThread;
	
	public SocketListener()
	{
		_runningThread = new Thread(new SocketRunner());
	}
	
	public void Start()
	{
		_runningThread.start();
	}
	
	private class SocketRunner implements Runnable
	{
		private ServerSocket _serverSocket;
		private Socket _socket;
		
		private SocketRunner()
		{
		}

		private void CreateSocket()
		{
			try 
			{
				_serverSocket = new ServerSocket(Constants.Socket_Server);
				_socket = _serverSocket.accept();
			} 
			catch (UnknownHostException e) 
			{
				e.printStackTrace();
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
			}
		}
		
		@Override
		public void run() 
		{
			while(true)
			{
				try 
				{
					CreateSocket();
					
					int current = 0;
					InputStream is = _socket.getInputStream();
					ObjectInputStream ois = new ObjectInputStream(is);
					String path = "";
					try 
					{
						path = (String)ois.readObject();
					} 
					catch (ClassNotFoundException e) 
					{
						e.printStackTrace();
					}
					
					String folders = path.substring(0, path.lastIndexOf('\\'));

					if (folders.length() > 0) 
					{
						File file = new File(Constants.Shared_Folder + folders);
						if (!file.exists()) 
						{
							file.mkdirs();
						}
					}

					byte[] mybytearray = new byte[Constants.File_Size];
					FileOutputStream fos = new FileOutputStream(Constants.Shared_Folder + path);
					BufferedOutputStream bos = new BufferedOutputStream(fos);
					int bytesRead = is.read(mybytearray, 0, mybytearray.length);
					current = bytesRead;
					while(bytesRead > -1)
					{
				         bytesRead =
				            is.read(mybytearray, current, (mybytearray.length-current));
				         if(bytesRead >= 0) current += bytesRead;
				    };
				    
					bos.write(mybytearray, 0, current);
					bos.flush();
					ois.close();
					bos.close();
					_socket.close();
				} catch (IOException e) 
				{
					e.printStackTrace();
				}
			}
		}
	}
}
